package FileUpload

import (
	"exercise/application/yiran/app"
	"exercise/application/yiran/app/libs"
	"exercise/common/constant"
	"io"
	"mime/multipart"
	"os"
	"path"
	"path/filepath"
	"time"
)

type local struct {
	folder   string
	filename string
	ext      string
}

func NewLocal(folder string, filename string, ext string) *local {
	return &local{
		folder:   folder,
		filename: filename,
		ext:      ext,
	}
}
func (l *local) UploadFile(file *multipart.FileHeader) (string, error) {
	//文件后缀
	var ext string = l.ext
	if ext == "" {
		ext = path.Ext(file.Filename)
	}
	//文件名
	var filename string = l.filename
	if filename == "" {
		filename = libs.TimestampToDate(time.Now().Unix(), constant.UnTimestampTemplate) + ext
	}

	//存放的文件夹
	folder := l.folder
	if folder == "" {
		folder = "images/"
	}

	//创建文件夹
	path := filepath.Join(app.YiRanPublicDir, folder)
	libs.CreateDetect(path)

	//文件全名
	fullName := filepath.Join(path, filename)
	//读取文件
	fileHandle, err := file.Open()
	if err != nil {
		return "", err
	}
	//创建文件
	out, err := os.Create(fullName)
	if err != nil {
		return "", err
	}
	defer func() {
		_ = fileHandle.Close()
		_ = out.Close()
	}()

	//file图片拷贝到新创建的文件中
	_, copyErr := io.Copy(out, fileHandle) // 传输（拷贝）文件
	if copyErr != nil {
		return "", err
	}

	return filepath.ToSlash(filepath.Join(folder, filename)), nil
}
